package com.mcy.springbatch.job;

import com.mcy.springbatch.entity.SysUser;
import com.mcy.springbatch.job.BaseJobConfig;
import com.mcy.springbatch.listener.ReadDataItemReadListener;
import com.mcy.springbatch.listener.WriteDataItemWriteListener;
import com.mcy.springbatch.reader.ReadUserDataFlatFileItemReader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.xml.bind.ValidationException;

/**
 * 读取与写出数据监听器Demo
 */
@Slf4j
@Configuration
public class KFileReadWriteDataDListenerJobConfig extends BaseJobConfig {

    @Autowired
    private ReadUserDataFlatFileItemReader readUserDataFlatFileItemReader;

    @Autowired
    private WriteDataItemWriteListener writeDataItemWriteListener;

    @Autowired
    private ReadDataItemReadListener readDataItemReadListener;

    @Bean
    public Job fileReaderJob() {
        return jobBuilderFactory.get("fileReaderJob")
                .incrementer(new RunIdIncrementer())
                .start(fileReaderStep())
                .build();
    }

    @Bean
    public Step fileReaderStep() {
        return stepBuilderFactory.get("fileReaderStep")
                .<SysUser, SysUser>chunk(20)
                .faultTolerant()
                .reader(readUserDataFlatFileItemReader)
                .listener(readDataItemReadListener)
                .writer(flatFileWriter())
                .listener(writeDataItemWriteListener)
                .build();

    }


    /**
     * 模拟写出出错
     * @return
     */
    @Bean
    public ItemWriter flatFileWriter(){
        return (ItemWriter<SysUser>) list -> {
            for (SysUser sysUser : list) {
                if(sysUser.getId() == 5){
                    throw new ValidationException("模拟写出数据出错");
                }
            }
        };
    }

}
